from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.utils import check_save_user_token
from users.models import User
from .models import OAuthQQUser


class QQAuthUserSerializer(serializers.Serializer):
    """openid绑定用户的序列化器"""
    # mobile password sms_code access_token(openid)
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        # 把加密的openid取出来解密
        access_token = attrs.pop('access_token')
        # 把原本的openid 重新添加到attrs 字典(以备后期create方法绑定使用)
        openid = check_save_user_token(access_token)
        if openid is None:
            raise serializers.ValidationError("openid无效")
        attrs['openid'] = openid
        # 校验验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs.get('mobile')
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        if real_sms_code is None or attrs.get('sms_code') != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误或已失效')

        # 拿手机号查询 user表 如果查询到说明手机号已注册,如果已注册在帮定密码是否和用户匹配
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码错误')
            # 如果用户已存在且密码正确 把正确的user对象存储到反序列化大字典中以备后期绑定使用
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 获取validated_data中的user, 如果能取到user说明用户已存在
        user = validated_data.get('user')
        # 如果取不到user则创建一个新用户
        if not user:
            user = User(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
            )
            user.set_password(validated_data.get('password'))
            user.save()
        # 把openid与用户绑定
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )
        # 把user返回
        return user
